import React, { useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { useVerifyOrderMutation } from "../../slices/ordersApiSlice";

/**
 * 验证支付组件
 * 该组件用于处理支付验证逻辑，通过订单ID和支付成功标志来验证支付状态
 */
const VerifyPayment = () => {
  // 使用react-router-dom的钩子获取当前location和导航函数
  const location = useLocation();
  const navigate = useNavigate();
  // 使用Apollo Client的钩子获取验证订单支付状态的mutation
  const [verifyOrder] = useVerifyOrderMutation();

  // 从URL查询参数中获取支付成功标志和订单ID
  const query = new URLSearchParams(location.search);
  const success = query.get("success");
  const orderId = query.get("orderId");

  // 当订单ID或支付成功标志变化时，触发支付验证逻辑
  useEffect(() => {
    // 定义一个异步函数来处理支付验证
    const verify = async () => {
      try {
        // 打印日志，开始验证支付
        console.log("Verifying payment for order ID:", orderId);
        // 调用验证订单支付状态的mutation，并传递订单ID和支付成功标志
        const response = await verifyOrder({ orderId, success }).unwrap();
        // 根据响应结果判断验证是否成功
        if (response.success) {
          // 如果验证成功，打印成功信息，并导航到订单成功的页面
          console.log("Verification successful:", response.order);
          navigate("/order-success", { state: { order: response.order } });
        } else {
          // 如果验证失败，打印失败信息，并导航到订单失败的页面
          console.log("Verification failed:", response.message);
          navigate("/order-failure");
        }
      } catch (error) {
        // 捕获验证过程中出现的错误，并导航到订单失败的页面
        console.error("Error verifying payment:", error);
        navigate("/order-failure");
      }
    };

    // 调用异步函数来处理支付验证
    verify();
  }, [orderId, success, verifyOrder, navigate]);

  // 渲染验证支付中的状态
  return <div>Verifying payment...</div>;
};

export default VerifyPayment;
